<template>
  <view class="chat-container">
    <!-- 聊天内容区域 -->
    <scroll-view 
      class="chat-content" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      @scrolltoupper="loadMoreMessages"
      upper-threshold="50"
      ref="chatScroll"
    >
      <!-- AI欢迎消息 -->
      <view class="message-item ai-message">
        <image class="avatar" :src="doctorInfo.imgUrl" mode="aspectFill"></image>
        <view class="message-content">
          <text class="message-text">{{welcomeMessage}}</text>
        </view>
      </view>

      <!-- 用户消息 -->
     <!-- <view class="message-item user-message" v-if="userSentMessage">
        <view class="message-content">
          <text class="message-text">{{ inputMessage }}</text>
        </view>
        <image class="avatar" src="/static/img/找医生.png" mode="aspectFill"></image>
      </view> -->
		
      <!-- 消息列表 -->
      <view 
        v-for="(msg, index) in messages" 
        :key="index" 
        class="message-item"
        :class="msg.isUser ? 'user-message' : 'ai-message'"
      >
        <image 
          v-if="!msg.isUser" 
          class="avatar" 
          :src="doctorInfo.imgUrl" 
          mode="aspectFill"
        ></image>
		   <image 
          v-if="msg.isUser" 
          class="avatar" 
          src="/static/img/找医生.png" 
          mode="aspectFill"
        ></image>
        <view class="message-content">
          <text class="message-text">{{ msg.content }}</text>
        </view>
    
      </view>

      <!-- 正在输入提示 -->
      <view class="message-item ai-message" v-if="isAiTyping">
        <image class="avatar" :src="doctorInfo.imgUrl" mode="aspectFill"></image>
        <view class="message-content typing">
          <view class="typing-indicator">
            <view class="dot"></view>
            <view class="dot"></view>
            <view class="dot"></view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-area">
      <input 
        class="message-input" 
        v-model="inputMessage" 
        placeholder="请输入您的问题" 
        confirm-type="send"
        @confirm="sendMessage"
      />
      <button class="send-btn" @tap="sendMessage">发送</button>
	  <button class="send-btn" @tap="goBack">返回</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      scrollTop: 0,
      isAiTyping: false,
      userSentMessage: false,
      doctorInfo: {},
      welcomeMessage: ''
    }
  },
  
  onLoad(options) {
    // 接收并解析医生信息
    if (options.doctorInfo) {
      try {
        this.doctorInfo = JSON.parse(decodeURIComponent(options.doctorInfo));
        // 如果有医生信息，更新欢迎消息
        if (this.doctorInfo.name) {
          this.welcomeMessage = `您好！我是${this.doctorInfo.name}医生，有什么可以帮您的吗？`;
        }
      } catch (error) {
        console.error('解析医生信息失败:', error);
      }
    }
    
    // 初始化页面
    setTimeout(() => {
      this.scrollToBottom();
    }, 300);
  },
  
  methods: {
    // 添加处理消息内容的方法
    processMessageContent(content) {
      if (!content) return '';
      // 移除<think>标签及其内容
      return content.replace(/<think>[\s\S]*?<\/think>/g, '');
    },
    
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      // 添加用户消息
      this.messages.push({
        content: this.inputMessage,
        isUser: true,
        time: new Date().getTime()
      });
      
      const userQuestion = this.inputMessage;
      this.inputMessage = '';
      this.userSentMessage = true;
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      // 显示AI正在输入
      this.isAiTyping = true;
      
      // 调用后端接口获取AI回复
      uni.request({
        url: 'http://localhost:8188/doctorai',
        method: 'POST',
        data: {
          message: userQuestion
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: (res) => {
          this.isAiTyping = false;
          
          if (res.statusCode === 200) {
            try {
              console.log('API Response:', res.data); // 调试日志
              
              const response = res.data;
              let messageContent = '';
              
              if (response && response.textResponse) {
                messageContent = response.textResponse;
              } else if (typeof response === 'string') {
                messageContent = response;
              } else {
                console.error('Unexpected response format:', response);
                messageContent = "抱歉，无法解析响应内容。";
              }
              
              // 移除<think>标签及其内容
              messageContent = messageContent.replace(/<think>[\s\S]*?<\/think>/g, '');
              
              console.log('Processed Message:', messageContent); // 调试日志
              
              this.messages.push({
                content: messageContent,
                isUser: false,
                time: new Date().getTime()
              });
              
              // 强制更新视图
              this.$forceUpdate();
              
            } catch (e) {
              console.error('处理响应失败:', e);
              this.messages.push({
                content: "抱歉，处理响应时出现错误。",
                isUser: false,
                time: new Date().getTime()
              });
            }
          } else {
            // 处理错误情况
            this.messages.push({
              content: "抱歉，我暂时无法回答您的问题，请稍后再试。",
              isUser: false,
              time: new Date().getTime()
            });
          }
          
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        },
        fail: (err) => {
          this.isAiTyping = false;
          console.error('请求失败:', err);
          
          // 显示错误消息
          this.messages.push({
            content: "网络连接失败，请检查您的网络设置后重试。",
            isUser: false,
            time: new Date().getTime()
          });
          
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      });
    },
    
    scrollToBottom() {
      // 获取消息列表高度并滚动到底部
      const query = uni.createSelectorQuery().in(this);
      query.select('.chat-content').boundingClientRect(data => {
        if (data) {
          this.scrollTop = data.height * 2; // 确保滚动到底部
        }
      }).exec();
    },
    
    loadMoreMessages() {
      // 加载更多历史消息的逻辑
      console.log('加载更多消息');
      // 实际应用中可以从服务器获取历史消息
    },

    formatTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    goBack() {
      // 修改为导航到consultation.vue页面
      uni.navigateTo({
        url: `/pages/consultation/consultation`
      });
    }
  }
}
</script>

<style lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  
  .chat-content {
    flex: 1;
    padding: 30rpx 30rpx 120rpx;
    overflow-y: auto;
    
    .message-item {
      display: flex;
      margin-bottom: 30rpx;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        background-color: #e0e0e0;
      }
      
      .message-content {
        max-width: 70%;
        padding: 20rpx;
        border-radius: 10rpx;
        margin: 0 20rpx;
        
        .message-text {
          font-size: 28rpx;
          line-height: 1.5;
          word-break: break-word;
        }
      }
      
      &.ai-message {
        align-self: flex-start;
        
        .message-content {
          background-color: #ffffff;
          color: #333;
          border-radius: 0 20rpx 20rpx 20rpx;
        }
      }
      
      &.user-message {
        flex-direction: row-reverse;
        align-self: flex-end;
        
        .message-content {
          background-color: #007AFF;
          color: #ffffff;
          border-radius: 20rpx 0 20rpx 20rpx;
        }
      }
      
      .typing {
        min-width: 80rpx;
        
        .typing-indicator {
          display: flex;
          align-items: center;
          
          .dot {
            width: 10rpx;
            height: 10rpx;
            border-radius: 50%;
            background-color: #999;
            margin: 0 5rpx;
            animation: typing 1.5s infinite ease-in-out;
            
            &:nth-child(1) {
              animation-delay: 0s;
            }
            
            &:nth-child(2) {
              animation-delay: 0.2s;
            }
            
            &:nth-child(3) {
              animation-delay: 0.4s;
            }
          }
        }
      }
    }
  }
  
  .input-area {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .message-input {
      flex: 1;
      height: 80rpx;
      background-color: #f5f5f5;
      border-radius: 40rpx;
      padding: 0 30rpx;
      font-size: 28rpx;
    }
    
    .send-btn {
      width: 120rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background-color: #007AFF;
      color: #ffffff;
      border-radius: 40rpx;
      margin-left: 20rpx;
      font-size: 28rpx;
    }
  }
}

@keyframes typing {
  0% {
    transform: translateY(0);
    opacity: 0.5;
  }
  50% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
  100% {
    transform: translateY(0);
    opacity: 0.5;
  }
}
</style> 